﻿using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;

namespace DynamicallyBuildUDFBasedOnSchema
{
	class Program
	{
		static Dictionary<string, TreeNode> _hierarchyRoot = new Dictionary<string, TreeNode>();
		static ActiveDirectorySchema _schema;
		static uint _structuralClassCount = 0;

		static void Main(string[] args)
		{
			////get schema
			//getSchema:
			//try
			//{
			//	_schema = ActiveDirectorySchema.GetCurrentSchema();
			//}
			//catch
			//{
			//	Console.WriteLine("Couldn't contact AD server.");
			//	goto getSchema;
			//	//return;
			//}

			//foreach (ActiveDirectorySchemaClass c in _schema.FindAllClasses())
			//{
			//	buildHierarchy(c);
			//	//				break;
			//}

			//foreach (KeyValuePair<string, TreeNode> kvp in _hierarchyRoot)
			//{
			//	Console.WriteLine(kvp.Key);
			//	outputTree(kvp.Value);
			//}

			//Console.WriteLine("Found {0} structural classes.", _structuralClassCount);

			////Process Schema
			//foreach (KeyValuePair<string, TreeNode> kvp in _hierarchyRoot)
			//{
			//	kvp.Value.CreateUDF();
			//}

			//Compilation.Compile(true);
			PopulateSQL.CreateAssembly("kbdb01.brumfield.biz", "ActiveDirectoryProxy");
		}

		static TreeNode buildHierarchy(ActiveDirectorySchemaClass c)
		{
			TreeNode parent = null;

			if (c.Type == SchemaClassType.Structural)
			{
				_structuralClassCount++;
			}

			if (c.Type != SchemaClassType.Auxiliary)
			{
				if (c.Name == c.SubClassOf.Name)
				{
					if (!_hierarchyRoot.ContainsKey(c.Name))
					{
						_hierarchyRoot.Add(c.Name, new TreeNode(c));
					}
					return _hierarchyRoot[c.Name];
				}
				else
				{
					parent = buildHierarchy(c.SubClassOf);
				}

				if (!(parent.ContainsKey(c.Name)))
				{
					parent.Add(c.Name, new TreeNode(c));
				}

				return parent[c.Name];
			}

			return null;
		}

		static void outputTree(TreeNode nodes)
		{
			outputTree(nodes, "|-");
		}

		static void outputTree(TreeNode nodes, string indent)
		{
			foreach (KeyValuePair<string, TreeNode> node in nodes)
			{
				Console.WriteLine("{0} {1}", indent, node.Key);
				outputTree(node.Value, indent + "|-");
			}
		}
	}
}
